package gui;

import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 * @author Ramy Refky 
 * */
public class HorizontalScrollBar extends JPanel implements MouseMotionListener {

	private static final long serialVersionUID = 1L;

	JLabel scrollButton;
	MainGui mg;
	WorkArea workArea;
	Actions actions;
	int scrollButtonWidth;
	double widthRatio;
	
	/**
	 * Constructor initializes Horizontal Scroll bar.
	 * @param MainGui
	 */
	public HorizontalScrollBar(MainGui mg) {
		this.mg=mg;
		workArea=mg.getWorkArea();
		actions=mg.getActions();
		
		setBounds(75,551,830,10);
		this.setBackground(Color.white);
		setBorder(BorderFactory.createLineBorder(Color.gray, 3));
		scrollButton = new JLabel();
		scrollButton.setOpaque(true);
		widthRatio = (workArea.getWidth()+0.0)/(this.getWidth());
		scrollButtonWidth = (int) (830/widthRatio);
		scrollButton.setBounds(0, 0,scrollButtonWidth,10);
		scrollButton.setVisible(true);
		scrollButton.setBackground(Color.gray.darker());
		scrollButton.setBorder(BorderFactory.createLineBorder(Color.gray, 3));
		this.add(scrollButton);

		addMouseMotionListener(this);

		setVisible(true);
		setLayout(null);

	}
	/**
	 * Adjusts the width of the Scroll button according to the zoom factor.
	 * */
	public void refreshBar(){
		widthRatio = (workArea.getWidth()+0.0)/(this.getWidth());
		scrollButtonWidth = (int) (830/widthRatio);
		scrollButton.setBounds(scrollButton.getX(),scrollButton.getY(),scrollButtonWidth,10);
		repaint();
	}	
	@Override
	public void mouseDragged(MouseEvent arg0) {
		
		mg.getAboutPanel().setVisible(false);
		
		int xPosition = arg0.getX();
		int newPosition = (int) xPosition - scrollButtonWidth / 2;
		int size= mg.getWorkArea().getWidth();
		
		if (newPosition < 0) {
			scrollButton.setBounds(0,0,scrollButtonWidth,10);
			workArea.setBounds(0,workArea.getY(),size,size);
		} else {
			if (newPosition > 830 - scrollButtonWidth) {
				scrollButton.setBounds(830 - scrollButtonWidth,0,scrollButtonWidth,10);
				workArea.setBounds(-size +830,workArea.getY(),size,size);
			} else {
				if (newPosition >= 0 && newPosition <= 830 - scrollButtonWidth) {
					scrollButton.setBounds(newPosition,0,scrollButtonWidth,10);
					workArea.setBounds((int) (-newPosition*widthRatio),workArea.getY(),size,size);
				}
			}
		}
	}
	@Override
	public void mouseMoved(MouseEvent arg0) {}

}
